package com.lxg.config;

import com.lxg.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author 陆小根
 * date: 2022/04/24
 * Description:自定义SpringSecurity相关配置
 */

@Configuration
public class SecurityConfigure extends WebSecurityConfigurerAdapter {


  @Autowired
  private MyUserDetailsService myUserDetailsService;

//  @Bean
//  public UserDetailsService userDetailsService() {
//
//    // 换成数据库实现
//
//    // 覆盖内存中的
//    InMemoryUserDetailsManager inMemoryUserDetailsManager =
//            new InMemoryUserDetailsManager();
//    inMemoryUserDetailsManager.createUser(User.withUsername("root").password("{noop}123").roles("admin").build());
//    return inMemoryUserDetailsManager;
//  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//    auth.userDetailsService(userDetailsService());
    auth.userDetailsService(myUserDetailsService);
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests() // 开启认证
            .mvcMatchers("/login.html").permitAll() // 放行操作
            .anyRequest().authenticated() // 所有请求开启认证
            .and()
            .formLogin() // 表单验证
            .loginPage("/login.html") // 指定自定义登录界面
            .loginProcessingUrl("/doLogin") // 处理的登录请求
            .usernameParameter("uname")
            .passwordParameter("passwd")
            .defaultSuccessUrl("/index.html", true) // 请求成功重定向到哪个页面
            .failureUrl("/login.html") // 登录失败重定向到我们的登录页面  错误信息保存在session作用域中
            // 配置注销
            .and()
            .logout() // 开启退出登录
            .logoutUrl("/logout")
            .logoutSuccessUrl("/login.html")
            .and()
            .csrf().disable() // 关闭 csrf保护
    ;
  }
}
